<?php

namespace App\Models;

class Cart extends Base
{
    protected $table = 'mall_cart';

    protected $casts = [
        'specs_info' => 'array',
    ];

    protected $appends = ['specs_info_show'];

    public function product() {
        return $this->belongsTo(Product::class, 'product_id');
    }


    public function setSpecsInfoAttribute($val) {
        $this->attributes['specs_info'] = $val;
    }

    public function reduction() {
        return $this->belongsTo(MallFullReduction::class, 'producer_id', 'merchant_id');
    }

    public function getSpecsInfoShowAttribute() {
        if (!$this->is_specs)
            return null;
        $arr = [];
        $info = $this->specs_info;
        unset($info['amount'], $info['vip_amount'], $info['stock'],$info['weight'], $info['key'], $info['vip_price'], $info['price']);
        foreach ($info as $key => $item) {
            $temp = [];
            $id = ltrim($key, 'specs_');
            $temp['key'] = Specs::fetch_title($id);
            $temp['value'] = $item;
            array_push($arr, $temp);
        }
        return $arr;
    }

    public function getProductSpecsAttribute() {
        $specs_info = $this->specs_info;
        $product = Product::find($this->product_id);
        if (!$product)
            return [];

        $arr_info = $product->specs_detail['info'];
        foreach ($arr_info as $key => $val) {
            $key = 0;
            foreach ($specs_info as $k => $v) {
                if ($val[$k] == $v) {
                    $key = $key + 1;
                }
            }
            if ($key == 2) {
                return $val;
            }
        }
    }


    public static function getFee($cart = []) {
        Cart::whereIn('id', $cart)->groupBy('producer_id');
    }
}
